package com.tc.es.utils;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ElasticSearchUtil {

    public static void upsert(ElasticsearchRestTemplate elasticsearchRestTemplate,
                              String id,
                              Document document,
                              Class clazz) {
        UpdateQuery.Builder updateQueryBuilder = UpdateQuery.builder(id)
                .withDocAsUpsert(true).withDocument(document);
        elasticsearchRestTemplate.update(updateQueryBuilder.build(), elasticsearchRestTemplate.getIndexCoordinatesFor(clazz));


    }


    public static List<Map<String, Object>> getFullIndex(RestHighLevelClient rhlClient,  String indexName)  {

        List<Map<String, Object>> fullIndex = new ArrayList<>();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.types("_doc");
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = null;
        try {
            searchResponse = rhlClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = searchResponse.getHits();
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsString =hit.getSourceAsMap();
                fullIndex.add(sourceAsString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }



        return fullIndex;
    }


    public static URI getIP(URI uri) {
        URI effectiveURI = null;
        try {
            // URI(String scheme, String userInfo, String host, int port, String
            // path, String query,String fragment)
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
        } catch (Throwable var4) {
            effectiveURI = null;
        }
        return effectiveURI;
    }

}